package ru.voice2blog.publisher.blogger;

import com.google.gdata.client.blogger.BloggerService;
import com.google.gdata.data.Entry;
import com.google.gdata.data.Feed;
import com.google.gdata.data.Person;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import com.google.gdata.util.common.base.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.voice2blog.common.Application;
import ru.voice2blog.common.V2BServiceAdapter;
import ru.voice2blog.common.exception.InitException;
import ru.voice2blog.common.exception.PrepareException;
import ru.voice2blog.common.exception.PublishException;
import ru.voice2blog.common.publisher.PublishResult;
import ru.voice2blog.common.publisher.Publisher;

import java.io.IOException;
import java.net.URL;
import java.util.Properties;


/**
 * User: ilya.ufo
 * Date: 09.03.11
 * Time: 23:44
 */
public class BloggerPublisher extends V2BServiceAdapter implements Publisher {

    private static final Logger log = LoggerFactory.getLogger(BloggerPublisher.class);

    private static final String POSTS_FEED_URI_SUFFIX = "/posts/default";
    private static final String FEED_URI_BASE = "http://www.blogger.com/feeds";
    private static final String METAFEED_URL = "http://www.blogger.com/feeds/default/blogs";

    private String userName;
    private BloggerService myService;
    private String feedUri;
    private String title;
    private String authorName;
    private Boolean isDraft = false;
    private String playerUrl;

    @Override
    public void init(Properties properties) throws InitException {
        userName = properties.getProperty("userName");
        title = properties.getProperty("title");
        authorName = properties.getProperty("authorName");
        String isDraft = properties.getProperty("authorName");
        if (!StringUtil.isEmpty(isDraft)) {
            this.isDraft = Boolean.valueOf(isDraft);
        }
        myService = new BloggerService(Application.INSTANCE.getAppName());
        try {
            myService.setUserCredentials(userName, properties.getProperty("userPassword"));
        } catch (AuthenticationException e) {
            throw new InitException("Error on authentificate", e);
        }
        playerUrl = properties.getProperty("playerUrl");
    }

    @Override
    public void prepare(Properties propertySet) throws PrepareException {
        String blogId;
        try {
            blogId = getBlogId(myService);
        } catch (Exception e) {
            throw new PrepareException("Error on creating blog item.", e);
        }
        feedUri = FEED_URI_BASE + "/" + blogId;
    }

    @Override
    public PublishResult publish(String soundUrl) throws PublishException {
        Entry myEntry = new Entry();
        myEntry.setTitle(new PlainTextConstruct(title));
        myEntry.setContent(new PlainTextConstruct(getContent(soundUrl)));
        Person author = new Person(authorName, null, userName);
        myEntry.getAuthors().add(author);
        myEntry.setDraft(isDraft);

        try {
            URL postUrl = new URL(feedUri + POSTS_FEED_URI_SUFFIX);
            Entry insert = myService.insert(postUrl, myEntry);
            String href = insert.getHtmlLink().getHref();
            log.info("Inserted new blogger entry with link {}", href);
            return new PublishResult(href, href != null);
        } catch (Exception e) {
            throw new PublishException("Error while publishing to blog.", e);
        }
    }

    private String getContent(String soundUrl) {
        return "<div style=\"display:block;width:400px;height:30px\">   <object width=\"100%\" height=\"100%\" id=\"audio_api\" name=\"audio_api\" data=\"" + playerUrl + "\" type=\"application/x-shockwave-flash\">   <param name=\"allowfullscreen\" value=\"true\">   <param name=\"allowscriptaccess\" value=\"always\">   <param name=\"quality\" value=\"high\">   <param name=\"cachebusting\" value=\"true\">   <param name=\"bgcolor\" value=\"#000000\">   <param name=\"flashvars\" value=\"config={'plugins':{'controls':{'fullscreen':false,'height':30,'autoHide':false}},'clip':{'autoPlay':false,'url':'" + soundUrl + "'},'playerId':'audio'}\"> </object>  </div>";
    }

    private static String getBlogId(BloggerService myService) throws ServiceException, IOException {
        final URL feedUrl = new URL(METAFEED_URL);
        Feed resultFeed = myService.getFeed(feedUrl, Feed.class);

        // If the user has a blog then return the id (which comes after 'blog-')
        if (resultFeed.getEntries().size() > 0) {
            Entry entry = resultFeed.getEntries().get(0);
            return entry.getId().split("blog-")[1];
        }
        throw new IOException("User has no blogs!");
    }
}
